﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaoPortal.Areas.Admin.Models;

namespace TaoPortal.Filters
{
    public class SysAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            SessionEnt _sessionEnt = httpContext.Session[TaoPortal.Common.PublicKey.IDENTITY_KEY] as SessionEnt;
            if (_sessionEnt != null)
            {
                if (!string.IsNullOrEmpty(this.Roles))
                {
                    if (this.Roles != null)
                    {
                        var roleList = this.Roles.Split(',');
                        var exceptList = roleList.Except(_sessionEnt.Roles.Split(','));
                        if (roleList.Length == exceptList.Count())
                        {
                            httpContext.Response.StatusCode = 403;
                            return false;
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
            else
                return false;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Response.StatusCode == 403)
                filterContext.HttpContext.Response.Redirect("/");
            else
                base.HandleUnauthorizedRequest(filterContext);
        }
    }
}